package com.v1.video.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.activity.SettingLoginActivity;
import com.v1.video.domain.CommentResultEntity;
import com.v1.video.domain.LoginInfo;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.ParamList;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.interfaces.CommentDataCallBack;
import com.v1.video.util.Logger;


public class CommentEditFragment extends DialogFragment {
    private String TAG = this.getClass().getSimpleName();
    private View mLayout;
    private EditText commend;
    private TextView sendButton;
    private CommentDataCallBack dataCallBack;
    private Context context;
    private String parentId = "";//回复人的id
    private String parentName;//回复人的名字

    public CommentEditFragment() {

    }

    public CommentEditFragment(CommentDataCallBack context) {
        this.context = (Context) context;
        this.dataCallBack = context;
    }

    public CommentEditFragment(Context context, CommentDataCallBack callback) {
        this.context = context;
        this.dataCallBack = callback;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setStyle(DialogFragment.STYLE_NORMAL,
        // android.R.style.Theme_Holo_Light_DialogWhenLarge_NoActionBar);//Theme_Holo_Light_DialogWhenLarge_NoActionBar
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void autoFocus() {
        (new Handler()).postDelayed(new Runnable() {
            public void run() {
                InputMethodManager inManager = (InputMethodManager) commend.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 500);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Window window = getDialog().getWindow();
        window.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mLayout = inflater.inflate(R.layout.video_comment_send_layout,
                container);
        getDialog().getWindow().setBackgroundDrawable(
                new ColorDrawable(context.getResources().getColor(android.R.color.transparent)));
        getDialog().getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        commend = (EditText) mLayout.findViewById(R.id.send_comment_edit);
        sendButton = (TextView) mLayout.findViewById(R.id.send_comment_button);
        if (!TextUtils.isEmpty(parentId)) {
            if (!TextUtils.isEmpty(parentName)) {
                commend.setHint("回复" + parentName);
            } else {
                commend.setHint("回复");
            }
        }
        // 点击阴影消失
        mLayout.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                int top = mLayout.findViewById(R.id.send_comment).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < top) {
                        dismissAllowingStateLoss();
                    }
                }
                return true;
            }
        });
        sendButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String content = commend.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(context, "评论内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (content.length() >= 140) {
                    Toast.makeText(context, "评论内容不能超过140个字符", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (LoginInfo.getInstance().isLogin()) {
                    sendButton.setClickable(false);
                    sendComment(dataCallBack.getObjectId(), dataCallBack.getObjectName(), content);
                } else {
                    Intent intent = new Intent(context, SettingLoginActivity.class);
                    intent.putExtra("loginFlag", 2);
                    context.startActivity(intent);
                }
            }
        });
        return mLayout;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
    }

    public void showCommentDialog(String parentId, String parentName, String type) {
        try {
            this.parentId = parentId;
            this.parentName = parentName;
            this.object_type = type;
            if (!isAdded()) {
                show(((FragmentActivity) context).getSupportFragmentManager(),
                        "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String object_type;

    public void setObjectType(String type) {
        object_type = type;
    }

    /**
     * 写评论信息
     */
    private void sendComment(String videoId, String objectName, String content) {
        String url = String.format(V1VideoHttpApi.COMMENT_SEND(), Constant.DEVICEID);
        Logger.i(TAG, "发送评论url=" + url);
        ParamList params = new ParamList();
        params.add(new ParamList.Parameter("sys_type", "1"));
        params.add(new ParamList.Parameter("object_type", object_type));
        params.add(new ParamList.Parameter("object_id", videoId));
        params.add(new ParamList.Parameter("object_name", objectName == null ? "" : objectName));
        params.add(new ParamList.Parameter("user_id", LoginInfo.getInstance().getUserId()));
        params.add(new ParamList.Parameter("content", content));
        params.add(new ParamList.Parameter("parent_id", parentId == null ? "" : parentId));
        RequestManager.getInstance().postRequest(context, url, params, CommentResultEntity.class, new RequestManager.OnResponseListener() {
            @Override
            public void onSuccess(Object object, int code, String message,String keyId) {
                Logger.i(TAG, "onSuccess.object=" + object.toString());
                sendButton.setClickable(true);
                if (object != null) {
                    CommentResultEntity entity = (CommentResultEntity) object;
                    if (entity != null && entity.getBody() != null && "1".equals(entity.getBody().getResultCode())) {
                        commend.setText("");
                        dismiss();
                        Toast.makeText(context, "评论成功", Toast.LENGTH_SHORT).show();
                        dataCallBack.notifyData();
                    } else {
                        if (entity != null && entity.getBody() != null && !TextUtils.isEmpty(entity.getBody().getMessgae())) {
                            Toast.makeText(context, entity.getBody().getMessgae(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }

            @Override
            public void onFailure(int code, String message) {
                Logger.i(TAG, message);
                sendButton.setClickable(true);
            }
        });
    }
}
